package com.sdp.right.cron;


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.Assert;

import com.sdp.core.bizc.utils.ApplicationContextUtils;
import com.sdp.right.db.sys_cron.service.ISysCronService;
import com.sdp.right.entity.SysCron;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Configuration
@EnableScheduling
public class ScheduledConfig implements SchedulingConfigurer{
	
	@Autowired
	private ISysCronService iSysCronService;
	
	@Autowired
    private ApplicationContext context;
	
	@Value("${sdp.systemNo}")
	private String systemNo;
	
	@Value("${sdp.startTimer}")
	private boolean startTimer;
	

	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		log.info("进入动态定时任务类******");
		if(!startTimer) {
			log.info("系统未开启定时任务******");
			return;
		}
		log.info("动态定时任务开始启动******");
		
		ThreadPoolTaskScheduler taskScheduler = ApplicationContextUtils.getBean(AsyncConfig.class).getThreadPoolTaskScheduler();
		taskRegistrar.setTaskScheduler(taskScheduler);
		
		//这里默认也启动权限模块的定时任务
		for(SysCron cron : iSysCronService.querySysCronBySystemNoAndRight(systemNo)) {
            Object task=null;
			try {
				task = context.getBean(Class.forName(cron.getTaskClass()));
			} catch (ClassNotFoundException e) {
                throw new IllegalArgumentException(cron.getTaskName()+" 任务有误", e);
            } catch (BeansException e) {
                throw new IllegalArgumentException(cron.getTaskClass() + "未纳入到spring管理", e);
            }
			Assert.isAssignable(ScheduledOfTask.class, task.getClass(), "定时任务类必须实现ScheduledOfTask接口");
			
			//将所有任务保存(为了不每次都查询数据库)
			TaskCollection.addTask(cron.getTaskClass(), cron);
	
			taskRegistrar.addTriggerTask(((Runnable) task),
                    triggerContext -> {
//                    	System.out.println(JSON.toJSONString(TaskCollection.getTask(cron.getTaskClass())));
                        return new CronTrigger(TaskCollection.getTask(cron.getTaskClass()).getTaskCron()).nextExecutionTime(triggerContext);
                    }
            );
			log.info("定时任务:"+cron.getTaskName()+"加载成功******");
		}
		
	}
	
}
